/**
 *@description 用户授权操作页面js
 *@author XieXing
 *@date 2020/8/18 22:46
 */
var table, form, layer, laydate, layedit, selectM, selectN, multiSelect;//当前页面全局定义 multiSelect多选框 TODO 继续优化
var tData;
var module = {
    /**
     *@description url集合
     *@author XieXing
     *@date 2020/8/18 22:45
     */
    URL: {
        getDataListUrl: '/user/getUserList',//获取数据接口
        getRoles: "/role/getRoles",
        updateStatusUrl: function (id, status) {//更新用户状态
            return '/user/' + id + '/' + status;
        },
        setUserAuth: '/user_authorization/setUserAuth', //设置用户权限
        getRoleIdsByUserId: '/user_authorization/getRoleIdsByUserId'

    },
    /**
     *@description 初始化
     *@author XieXing
     *@date 2020/8/18 22:46
     */
    init: function () {
        layui.extend({
            selectN: '/static/assets/layui-extends/selectN',
            selectM: '/static/assets/layui-extends/selectM'
        }).use(['form', 'table', 'layer', 'laydate', 'layedit', 'selectN', 'selectM'], function () {
            table = layui.table;
            form = layui.form;
            layer = layui.layer;
            laydate = layui.laydate;
            layedit = layui.layedit;
            selectM = layui.selectM;
            selectN = layui.selectN;
            var pageData = page.pageData();
            var loading = layer.load(0);//开启延迟加载
            table.render({
                elem: '#datagrid',
                id: 'datagrid',
                url: module.URL.getDataListUrl,
                method: "GET",
                cols: [[
                    {type: 'radio', fixed: 'left'},
                    {type: 'numbers', title: '序号', fixed: "left"},
                    {
                        field: 'userName',
                        title: '姓名',
                        align: 'center',
                        width: '10%'
                    },
                    {
                        field: 'userGender', title: '性别', width: '10%', align: 'center',
                        templet: function (d) {
                            if (d.userGender == 1) {//男
                                return "男";
                            } else if (d.userGender == 2) {//女
                                return "女";
                            } else {
                                return "未填写";
                            }
                        }
                    },
                    {field: 'userAccount', title: '账号', width: '10%'},

                    {
                        field: 'userPhone',
                        title: '电话',
                        align: 'center',
                        width: '10%'
                    },
                    {field: 'userEmail', title: '邮箱', align: 'center', width: '15%'},
                    {field: 'userAddress', title: '地址', align: 'center', width: '10%'},


                    {
                        field: 'userAddTime',
                        title: '添加时间',
                        align: 'center',
                        width: '15%',
                    },
                    {field: 'userSysId', title: '所属系统', align: 'center', width: '10%'},
                    {field: 'userAddby', title: '添加人姓名', align: 'center', width: '10%'},
                    {field: 'userUpdateTime', title: '修改时间', align: 'center', width: '15%'},
                    {field: 'userUpdateby', title: '修改人姓名', align: 'center', width: '10%'},
                    {field: 'userIntroduction', title: '用户简介', align: 'center', width: '10%'},
                    {field: 'userRemark', title: '备注', align: 'center', width: '10%'},
                    {
                        field: 'userType', title: '用户类型', align: 'center', width: '10%',
                        templet: function (d) {
                            if (d.userType == 1) {
                                return "普通用户";
                            } else {
                                return "特殊用户";
                            }
                        }
                    },
                    {
                        field: 'userIsEnabled', title: '状态', align: 'center', width: '12%', fixed: 'right',
                        templet: function (d) {
                            var checked = "";
                            if (d.userIsEnabled == 1) {
                                checked = "checked=true";
                            }
                            return "<input type='checkbox' " + checked + " id=" + d.id + " userName = " + d.userName + " name='userIsEnabled' lay-skin='switch' lay-text='启用|禁用' lay-event='test' lay-filter='switch'>"
                        }
                    },
                    {
                        field: '', title: '授权', align: 'center', width: '12%', fixed: 'right',
                        templet: function (d) {
                            return "<button class='layui-btn layui-icon layui-icon-auz' type='button' lay-event='userAuth'>授权</button>";
                        }
                    }
                ]],
                height: pageData.tableHeight,
                limit: pageData.limit,
                limits: pageData.limits,
                page: true,
                response: {
                    statusCode: 200
                },
                parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": res.code, //解析接口状态
                        "msg": res.stateInfo, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.list //解析数据列表
                    };
                },
                done: function (res, curr, count) {
                    var perPageMax = $(".layui-laypage-limits select option:last-child").val();//每页最大条数
                    page.tableLoadAll(count, perPageMax);//加载全部
                    layer.close(loading);//关闭延迟加载
                }
            });

            //监听单元格事件
            table.on('tool(datagrid)', function (obj) {
                if (obj.event === 'userAuth') {
                    module.edit_model("用户授权", module.URL.setUserAuth, obj.data);
                }
            });

            /**
             *@description 监听表格中的switch
             *@author XieXing
             *@date 2020/8/18 22:48
             */
            form.on('switch(switch)', function (data) {
                var userId = $(this).attr("id");
                var status = data.elem.checked ? 1 : 0;
                var loading = layer.load(1);
                $.post(module.URL.updateStatusUrl(userId, status), {}, function (result) {
                    if (result && result.code === 200) {
                        layer.closeAll();
                        $("#btnSearch").trigger("click");
                    } else {
                        layer.close(loading);
                        layer.msg(result.err, {icon: 2, time: 2000});
                        return false;
                    }
                });
            });


            /**
             *@description 获取角色
             *@author XieXing
             *@date 2020/10/12 14:13
             */
            $.get(module.URL.getRoles, {}, function (result) {
                if (result.code == 200) {
                    var data = result.data;
                    tData = data;
                    //多选标签-所有配置
                    multiSelect = selectM({
                        //元素容器【必填】
                        elem: '#roles'
                        //候选数据【必填】
                        , data: data
                        //默认值
                        , selected: []
                        //最多选中个数，默认5
                        , max: data.length
                        //input的name 不设置与选择器相同(去#.)
                        , name: 'roles'
                        //值的分隔符
                        , delimiter: ','
                        //候选项数据的键名
                        , field: {idName: 'id', titleName: 'roleName'}
                    });
                } else {
                    layer.msg(result.stateInfo, {icon: 2, time: 2000});
                }
            });
            /**
             *@description 点击查询
             *@author XieXing
             *@date 2020/7/30 11:34
             */
            $("#btnSearch").on("click", function () {
                var qm = {};
                $("#queryForm").serializeArray().forEach(function (each) {
                    qm[each.name] = each.value;
                });
                var cur = parseInt($(".layui-laypage-skip input").val()) || 1;//当前页
                var limit = parseInt($(".layui-laypage-limits select").val()) || 10;//当前每页条数
                table.reload('datagrid', {
                    where: qm,
                    page: {curr: cur, limit: limit}
                });
                return false;
            });

            /**
             *@description 重置
             *@author XieXing
             *@date 2020/8/16 18:08
             */
            $("#btnReset").click(function () {
                $("#queryForm")[0].reset();
                $("#btnSearch").trigger("click");//触发查询操作
            });
        });
    },

    /**
     *@description 编辑弹出层
     *@author XieXing
     *@date 2020/8/18 22:00
     */
    edit_model: function (modelName, url, rowData) {
        layer.open({
            type: 1,
            area: ['80%', '60%'],
            title: modelName,
            content: $("#dataModel"),
            offset: ['20px'],
            btn: ['提交', '取消'],
            btn1: function (index, layero) {
                $("#formSubmitBtn").trigger("click");
                return false;
            },
            btn2: function (index, layero) {
                $("#dataModel form")[0].reset();
                layer.closeAll();
                return false;
            },
            cancel: function (layero, index) {
                $("#dataModel form")[0].reset();
                layer.closeAll();
            },
            success: function (layero, index) {
                if (rowData) {
                    module.getData(rowData);//非新增操作回填数据
                    /**
                     *@description 获取当前用户的角色
                     *@author XieXing
                     *@date 2020/10/13 17:03
                     */
                    $.post(module.URL.getRoleIdsByUserId, {userId: rowData.id}, function (result) {
                        multiSelect.set(result);
                    });
                }
                form.on('submit(form_submit_btn)', function (data) {
                    var data = data.field;
                    // data.roles = data.roles.join(",");
                    if (rowData) { //rowData 存在表示修改用户信息
                        data.userId = rowData.id;
                    }
                    data.roles = multiSelect.values.join(",");
                    data.userGender = $("input[name=userGender_t]:checked").val();
                    var loading = layer.load(1);
                    $.post(url, data, function (result) {
                        if (result && result.code === 200) {
                            layer.closeAll();
                            $("#dataModel form")[0].reset();
                            $("#btnSearch").trigger("click");
                        } else {
                            layer.close(loading);
                            layer.msg(result.err, {icon: 2, time: 2000});
                            return false;
                        }
                    });
                    return false;
                });
            }
        });
    },
    /**
     *@description 对象回填数据
     *@author XieXing
     *@date 2020/8/17 15:02
     */
    getData: function (data) {
        for (var k in data) {
            $("input[name=" + k + "],select[name=" + k + "],textarea[name=" + k + "]").val(data[k]);
        }
        $("input[type=radio][value=" + data['userGender'] + "]").attr("checked", "checked");//给单选框赋值
        if (data.userIsEnabled == 1) {
            $("input[type=checkbox]").attr("checked", true);//给单选框赋值
        } else {
            $("input[type=checkbox]").attr("checked", false);//给单选框赋值
        }
        form.render();
    }
};

module.init();//运行初始化函数